package com.isoft.illustrationsdraw.controller;

import com.isoft.illustrationsdraw.exception.TokenExpiredException;
import com.isoft.illustrationsdraw.exception.TokenInvalidException;
import com.isoft.illustrationsdraw.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/auth")
public class AuthController {

    @Autowired
    private AuthService authService;

    /**
     * Generate and send a magic link to the provided email.
     *
     * @param email the email address to send the magic link to
     * @return ResponseEntity indicating success or failure
     */
    @PostMapping("/magic-link")
    public ResponseEntity<String> generateAndSendMagicLink(@RequestParam String email) {
        try {
            // Generate the magic link
            String magicLink = authService.generateMagicLink(email);
            if (magicLink == null) {
                return ResponseEntity.badRequest().body("Failed to generate magic link.");
            }

            // Send the magic link to the email
            boolean isSent = authService.sendMagicLink(email, magicLink);
            if (!isSent) {
                return ResponseEntity.status(500).body("Failed to send magic link.");
            }

            return ResponseEntity.ok("Magic link sent successfully.");
        } catch (Exception e) {
            return ResponseEntity.status(500).body("An error occurred: " + e.getMessage());
        }
    }

    /**
     * Handle login using the magic link token.
     *
     * @param token the token from the magic link
     * @return ResponseEntity with the long-term token or an error message
     */
    @GetMapping("/login")
    public ResponseEntity<String> loginWithMagicLink(@RequestParam String token) {
        try {
            // Use the token to generate a long-term token
            String longTermToken = authService.keepLoggedIn(token);
            if (longTermToken == null) {
                return ResponseEntity.badRequest().body("Invalid or expired magic link token.");
            }

            return ResponseEntity.ok(longTermToken);
        } catch (Exception e) {
            return ResponseEntity.status(500).body("An error occurred: " + e.getMessage());
        }
    }

    /**
     * Refresh long-term token if expired but not older than 5 days.
     *
     * @param token the long-term token to refresh
     * @return ResponseEntity with the new long-term token or an error message
     */
    @PostMapping("/refresh-token")
    public ResponseEntity<String> refreshLongTermToken(@RequestParam String token) {
        try {
            // 尝试刷新长效令牌
            String refreshedToken = authService.refreshLongTermToken(token);
            if (refreshedToken == null) {
                // 如果返回 null，说明令牌有效
                return ResponseEntity.badRequest().body("Token is still valid.");
            }

            // 如果成功刷新令牌，返回新令牌
            return ResponseEntity.ok(refreshedToken);
        } catch (TokenInvalidException e) {
            // 如果令牌无效，返回 400 错误
            return ResponseEntity.badRequest().body("The token is not a valid long-term token!");
        } catch (TokenExpiredException e) {
            // 如果令牌过期超过 5 天，返回 410 错误
            return ResponseEntity.status(HttpStatus.GONE).body("The token has expired for more than 5 days. Please log in again.");
        } catch (Exception e) {
            // 捕获其他异常，返回 500 错误
            return ResponseEntity.status(500).body("An error occurred: " + e.getMessage());
        }
    }

}

// 生成的第一个长效token：
// eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxODc0MTEzNzQwODg2NzgxOTU0IiwidGlkIjoxODc0MTE0NzU3MjQ2MzMyOTI5LCJleHAiOjE3MzYyNjM1NTJ9.KOtEA_Nob7oSRXdf_1b-uMTYccwY-AlFp1pmwR9q3GU
// 1874113740886781954 
// 生成的第二个长效token:
// eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxODc0MzMwMjQzNTk5MDM2NDE3IiwiZXhwIjoxNzM2MzE1MDU5fQ.mGC8qSsbjNGGumyrb8Hx5F8_f5sdLZkZGrH1DllyKL8
// 1874330243599036417